package com.briup.labs.service.impl;

import com.briup.labs.mapper.SmartDeviceTypeMapper;
import com.briup.labs.pojo.PageBean;
import com.briup.labs.pojo.SmartDeviceType;
import com.briup.labs.service.SmartDeviceTypeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SmartDeviceTypeServiceImpl implements SmartDeviceTypeService {

    @Autowired
    private SmartDeviceTypeMapper smartDeviceTypeMapper;

    @Override
    public List<SmartDeviceType> all() {
       return smartDeviceTypeMapper.all();
    }

    @Override
    public PageBean<SmartDeviceType> list(String pageNum, String pageSize, String key) {
        //创建PageBean对象
        PageBean<SmartDeviceType> pageBean = new PageBean<>();

        //检测数据输入格式
        int PN = 0;
        int PS = 0;
        try {
            PN = Integer.parseInt(pageNum);
            PS = Integer.parseInt(pageSize);
        } catch (Exception e) {
            pageBean.setTotal(null);
            pageBean.setItems(null);
            return pageBean;
        }

        //开启分页查询 PageHelper
        PageHelper.startPage(PN, PS);

        //调用mapper
        List<SmartDeviceType> smartDeviceTypes = smartDeviceTypeMapper.list(key);

        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当夜数据
        Page<SmartDeviceType> page = (Page<SmartDeviceType>) smartDeviceTypes;

        //把数据填充到PageBean对象中
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());
        //new pageInfo<>();
        return pageBean;
    }

    @Override
    public void saveOrUpdate(SmartDeviceType smartDeviceType) {
        //数据表没有设置自增
        List<SmartDeviceType> types = smartDeviceTypeMapper.all();
        for (SmartDeviceType type : types) {
            if (Objects.equals(smartDeviceType.getId(), type.getId())) {
                //修改
                smartDeviceTypeMapper.update(smartDeviceType);
                return;
            }
        }
        //添加
        smartDeviceTypeMapper.add(smartDeviceType);
    }

    @Override
    public void delete(String id) {
        //删除type
        smartDeviceTypeMapper.delete(id);
        //删除device
        smartDeviceTypeMapper.deleteDevice(id);
    }
}
